package ink.tsg.wx.service.impl;

import cn.hutool.crypto.digest.DigestAlgorithm;
import cn.hutool.crypto.digest.Digester;
import ink.tsg.wx.service.ITestService;
import lombok.extern.slf4j.Slf4j;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class TestServiceImpl implements ITestService {

    private static final String TOKEN = "abc";

    @Override
    public void hellowx(HttpServletRequest request, HttpServletResponse response) {
        String signature = request.getParameter("signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        String echostr = request.getParameter("echostr");
        // 1）将token、timestamp、nonce三个参数进行字典序排序
        String[] strs = new String[]{TOKEN,timestamp,nonce};
        Arrays.sort(strs);
        // 2）将三个参数字符串拼接成一个字符串进行sha1加密
        String str = strs[0]+strs[1]+strs[2];
        Digester md5 = new Digester(DigestAlgorithm.SHA1);
        String digestHex = md5.digestHex(str);
        // 3）开发者获得加密后的字符串可与signature对比，标识该请求来源于微信
        if(digestHex.equals(signature)){ // 校验成功
            PrintWriter out = null;
            try {
                out = response.getWriter();
                out.print(echostr);
                out.flush();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else{  // 校验失败
            log.error("签名校验失败！");
        }
    }

    @Override
    public Map<String, String> parseuserMSG(HttpServletRequest request,HttpServletResponse response) {
        try {
            SAXReader saxReader = new SAXReader();
            Document document = saxReader.read(request.getInputStream());
            Element rootElement = document.getRootElement();
            List<Element> elements = rootElement.elements();
            Map<String, String> resultMap = new HashMap<>();
            for (Element e:elements) {
                resultMap.put(e.getName(),e.getStringValue());
            }
            // 获取到的用户发送的消息
            System.out.println(resultMap);
            // 回复用户的消息
            returnMSG(resultMap,response);

        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * @Author dzsg
     * @Description 回复用户的消息
     *  <xml>
     *   <ToUserName><![CDATA[toUser]]></ToUserName>
     *   <FromUserName><![CDATA[fromUser]]></FromUserName>
     *   <CreateTime>12345678</CreateTime>
     *   <MsgType><![CDATA[text]]></MsgType>
     *   <Content><![CDATA[你好]]></Content>
     * </xml>
     * @Date 2021/2/25 11:24
     * @Param [resultMap, response]
     * @return void
     **/
    private void returnMSG(Map<String, String> resultMap, HttpServletResponse response) throws InterruptedException {
        response.setCharacterEncoding("UTF-8");
        String msg ="<xml><ToUserName><![CDATA["+resultMap.get("FromUserName")+"]]></ToUserName><FromUserName><![CDATA["+resultMap.get("ToUserName")+"]]></FromUserName><CreateTime>12345678</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[你好]]></Content></xml>";
        PrintWriter out = null;
        try {
            out = response.getWriter();
            out.print(msg);
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
